﻿#include "PortStateMonitor.h"
#include "Controller/modbusrtucontroller.h"
#include <QThread>
#include <QVariant>
#include "global.h"
PortStateMonitor::PortStateMonitor(QObject *parent) : QObject(parent)
{

}

PortStateMonitor::~PortStateMonitor()
{
    pPortController->deleteLater();
    pPortController = nullptr;
}

void PortStateMonitor::RunTask()
{
    QByteArray responseData;
    while(1)
    {
        QVector<bool> status;
        if(pPortController->modbus_02MultiRead(1,0,5,status)){
            emit sig_portMessageProcess(status);
        }

        while(!que_Cmd.isEmpty()){
            auto& cmd = que_Cmd.front();
            cmd.excute(pPortController);
            que_Cmd.pop_front();
        }
        QThread::msleep(1000);
    }
}

void PortStateMonitor::openDoor(int index)
{
    Modbus_WriteCmd cmd;
    cmd.Node = 1;
    cmd.Count = 1;
    cmd.KeyWord = 0x05;
    cmd.RegAddr = index;
    cmd.RegsValue.push_back(true);

    que_Cmd.push_back(cmd);
}

void PortStateMonitor::slot_PortStateMonitorInit()
{
    pPortController = new ModbusRtuController();
    if(!pPortController->ModbusUsart_Init("COM4",9600,8,1,0)){
        mylog<<"init port Uart failed!";
        return;
    }
    RunTask();
}
